﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Dynamic;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Threading.Tasks;

namespace TurboTemplate
{
    public partial class MainForm : Form
    {

        private bool m_IsLoading;
        private Profile m_CurrentProfile;
        private TransformInstructions m_CurrentProcedure;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {

            GeneratorConfiguration.Instance.TemplateSplitDistance = spltTemplate.SplitterDistance;
            GeneratorConfiguration.Instance.TemplateSplitOrientation = spltTemplate.Orientation;
            GeneratorConfiguration.Instance.MainLRSplitDistance = spltMainLR.SplitterDistance;
            GeneratorConfiguration.Instance.SourcesSplitDistance = spltSources.SplitterDistance;
            GeneratorConfiguration.Instance.SourceTabIndex = tabSource.SelectedIndex;

            GeneratorConfiguration.Instance.WindowState = this.WindowState;
            GeneratorConfiguration.Instance.WindowLocation = this.Location;
            if (this.WindowState == FormWindowState.Normal)
            {
                GeneratorConfiguration.Instance.WindowSize = this.Size;
            }
            GeneratorConfiguration.Instance.LastLoadedProfile = cboProfiles.SelectedItem != null ? ((Profile)cboProfiles.SelectedItem).Filename : null;
            GeneratorConfiguration.SaveConfiguration();
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            spltTemplate.Orientation = GeneratorConfiguration.Instance.TemplateSplitOrientation;

            if (GeneratorConfiguration.Instance.MainLRSplitDistance > 0)
                spltMainLR.SplitterDistance = GeneratorConfiguration.Instance.MainLRSplitDistance;
            if (GeneratorConfiguration.Instance.TemplateSplitDistance > 0)
                spltTemplate.SplitterDistance = GeneratorConfiguration.Instance.TemplateSplitDistance;
            if (GeneratorConfiguration.Instance.SourcesSplitDistance > 0)
                spltSources.SplitterDistance = GeneratorConfiguration.Instance.SourcesSplitDistance;
            tabSource.SelectedIndex = GeneratorConfiguration.Instance.SourceTabIndex;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            GeneratorConfiguration.LoadConfiguration();

            if (GeneratorConfiguration.Instance.WindowLocation != System.Drawing.Point.Empty)
                this.Location = GeneratorConfiguration.Instance.WindowLocation;
            if (GeneratorConfiguration.Instance.WindowSize != System.Drawing.Size.Empty)
                this.Size = GeneratorConfiguration.Instance.WindowSize;

            this.WindowState = GeneratorConfiguration.Instance.WindowState;

            m_IsLoading = true;
            Load_Profiles();
            Load_Templates();
            Load_ConnectionString();
            m_IsLoading = false;

            if (GeneratorConfiguration.Instance.LastLoadedProfile != null)
            {
                SelectProfile(GeneratorConfiguration.Instance.LastLoadedProfile);
            }
            UpdateUI();
        }

        private void Load_Profiles()
        {
            bool wasLoading = m_IsLoading;
            m_IsLoading = true;

            cboProfiles.DisplayMember = "Name";
            cboProfiles.DataSource = ProfileHelper.GetProfiles();
            cboProfiles.SelectedItem = null;

            m_IsLoading = wasLoading;
        }

        private void Load_Templates()
        {
            bool wasLoading = m_IsLoading;
            m_IsLoading = true;

            var templates = TemplateHelper.GetTemplates();

            cboTemplates.DisplayMember = "Name";
            cboTemplates.DataSource = templates;
            cboTemplates.SelectedItem = null;
            
            m_IsLoading = wasLoading;
        }

        private void Load_ConnectionString()
        {
            bool wasLoading = m_IsLoading;
            m_IsLoading = true;

            cboConnectionStrings.Items.Clear();
            cboConnectionStrings.Items.Add("New");
            foreach (string s in GeneratorConfiguration.Instance.ConnectionStrings)
            {
                cboConnectionStrings.Items.Add(s);
            }

            m_IsLoading = wasLoading;
        }
       
        private void Refresh_Db()
        {
            var schema = SchemaHelper.GetDbSchema((string)cboConnectionStrings.SelectedItem);

            cboProcedures.DisplayMember = "SPECIFIC_NAME";
            cboProcedures.DataSource = schema.Procedures;

            cboTables.DisplayMember = "TABLE_NAME";
            cboTables.DataSource = schema.Tables;
            cboTables.SelectedItem = null;

        }

        private void Refresh_Profile()
        {
            if (m_CurrentProfile == null || m_IsLoading)
            {
                m_IsLoading = true;
                
                SelectConnectionString(null);
                SelectProcedure(null);
                SelectTemplate(null);
                lstToGenerate.Items.Clear();
                tvLists.Nodes.Clear();

                m_IsLoading = false;
                return;
            }

            m_IsLoading = true;

            SelectConnectionString(m_CurrentProfile.SourcedFromConnection);
            SelectProcedure(m_CurrentProfile.ChosenProcedureID);
            SelectTemplate(m_CurrentProfile.ChosenTemplateID);

            lstToGenerate.Items.Clear();
            foreach (var p in m_CurrentProfile.TransformList)
            {
                CreateLviForProcedure(p);
            }

            Load_Lists();

            m_IsLoading = false;
        }

        private void Load_Lists()
        {
            if (m_CurrentProfile == null || m_CurrentProfile.ListSource == null)
                return;

            //var root = new ListWithName("Test ");
            //root = root.AddChildList("Chris");
            //var sandy = root.AddChildList("Sandy");
            //sandy.Add("Tom");
            //sandy.Add("Tai");
            //root.Add("Karl");
            //root.Add("Susan");
            //root.Add("Paula");
            //var sue = root.AddChildList("Sue");
            //sue.Add("Josie");
            //sue.Add("Claire");
            //sue.Add("Clare");

            //m_CurrentProfile.ListSource.Add(root);

            tvLists.Nodes.Clear();
            foreach (var list in m_CurrentProfile.ListSource)
            {
                Add_ListsToTree(null, list);
            }

            tvLists.ExpandAll();
        }

        private void Add_ListsToTree(TreeNode parent, ListWithName list)
        {
            TreeNode listNode = new TreeNode(list.Name);
            listNode.Tag = list;
            if (list.ChildLists.Count > 0)
                listNode.NodeFont = new Font(tvLists.Font, FontStyle.Bold);

            if (parent == null)
                tvLists.Nodes.Add(listNode);
            else
                parent.Nodes.Add(listNode);

            foreach (var nextList in list.ChildLists)
            {
                Add_ListsToTree(listNode, nextList);
            }

            //foreach (var textItem in list)
            //{
            //    TreeNode textNode = new TreeNode(textItem);
            //    listNode.Nodes.Add(textNode);
            //}
        }

        private void SelectConnectionString(string constr)
        {
            cboConnectionStrings.SelectedItem = null;
            cboConnectionStrings.SelectedItem = constr;
        }

        private void SelectProfile(string id)
        {
            cboProfiles.SelectedItem = null;
            foreach (Profile p in cboProfiles.Items)
            {
                if (p.Filename == id)
                {
                    cboProfiles.SelectedItem = p;
                    break;
                }
            }
        }

        private void SelectProcedure(string id)
        {
            cboProcedures.SelectedItem = null;
            foreach (SchemaStoredProcedure p in cboProcedures.Items)
            {
                if (p.SPECIFIC_NAME == id)
                {
                    cboProcedures.SelectedItem = p;
                    break;
                }
            }
        }

        private void SelectTemplate(string id)
        {
            cboTemplates.SelectedItem = null;
            foreach (TransformTemplate t in cboTemplates.Items)
            {
                if (t.FileName == id)
                {
                    cboTemplates.SelectedItem = t;
                    break;
                }
            }
        }

        private void SaveProfileFromUI()
        {
            if (m_CurrentProfile == null || m_IsLoading)
            {
                return;
            }

            if (cboConnectionStrings.SelectedItem != null)
                m_CurrentProfile.SourcedFromConnection = ((string)cboConnectionStrings.SelectedItem);
            else
                m_CurrentProfile.SourcedFromConnection = null;

            if (cboProcedures.SelectedItem != null)
                m_CurrentProfile.ChosenProcedureID = ((SchemaStoredProcedure)cboProcedures.SelectedItem).SPECIFIC_NAME;
            else
                m_CurrentProfile.ChosenProcedureID = null;

            if (cboTemplates.SelectedItem != null)
                m_CurrentProfile.ChosenTemplateID = ((TransformTemplate)cboTemplates.SelectedItem).FileName;
            else
                m_CurrentProfile.ChosenTemplateID = null;

            SynchroniseProcedureListWithProfile();
            m_CurrentProfile.Save(m_CurrentProfile.Filename);
        }

        private void SynchroniseProcedureListWithProfile()
        {
            if (m_CurrentProfile == null || m_IsLoading)
                return;

            m_CurrentProfile.TransformList.Clear();

            foreach (ListViewItem lvi in lstToGenerate.Items)
            {
                var tag = lvi.Tag as TransformInstructions;
                m_CurrentProfile.TransformList.Add(tag);
            }
        }

        private void PushTemplatesFromSourceToGenerateItems()
        {

            // Swap over the dead templates we've already used
            foreach (var t in TemplateHelper.GetTemplates())
            {
                foreach (ListViewItem lvi in lstToGenerate.Items)
                {
                    var tag = lvi.Tag as TransformInstructions;
                    if (tag.Template.FileName == t.FileName)
                    {
                        tag.Template = t.Clone() as TransformTemplate;
                        lvi.SubItems[1].Text = tag.Template.Name;
                    }
                }
            }

        }
        
        private void cboProfiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (m_IsLoading)
                return;

            if (cboProfiles.SelectedItem == Profile.NewProfile) // New
            {
                using (NewProfileDialog f = new NewProfileDialog())
                {
                    if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        Profile newProfile = new Profile()
                        {
                            Name = f.ProfileName,
                            SourcedFromConnection = (string)cboConnectionStrings.SelectedItem
                        };

                        newProfile.Filename = ProfileHelper.GetFileNameForNewProfile(newProfile);
                        newProfile.Save(newProfile.Filename);

                        m_CurrentProfile = newProfile;
                        //SaveProfileFromUI();
                        Load_Profiles();

                        SelectProfile(m_CurrentProfile.Filename);
                    }
                }
            }
            else
            {
                m_CurrentProfile = (Profile)cboProfiles.SelectedItem;
                Refresh_Profile();
            }
            UpdateUI();
        }

        private void btnDeleteProfile_Click(object sender, EventArgs e)
        {
            if (m_CurrentProfile == null)
                return;

            System.IO.File.Delete(m_CurrentProfile.Filename);
            Load_Profiles();
            Refresh_Profile();

        }

        private void cboConnectionStrings_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboConnectionStrings.SelectedIndex == 0) // New
            {
                string c = SchemaHelper.DataLinksConnection("");
                if (c.Length > 0 && !cboConnectionStrings.Items.Contains(c))
                {
                    int i = cboConnectionStrings.Items.Add(c);
                    GeneratorConfiguration.Instance.ConnectionStrings.Add(c);
                    cboConnectionStrings.SelectedIndex = i;
                }
            }
            else
            {
                Refresh_Db();
            }
            SaveProfileFromUI();
            UpdateUI();
        }

        private void cboProcedures_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveProfileFromUI();
            UpdateUI();
        }

        private void cboTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveProfileFromUI();
            UpdateUI();
        }

        private void cboProcedures_TextChanged(object sender, EventArgs e)
        {
            UpdateUI();
        }

        private void cboTemplates_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveProfileFromUI();
            UpdateUI();
        }

        private void lnkTemplates_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            using (var f = new TemplateEditorDialog())
            {
                f.ShowDialog();
            }
            Load_Templates();
            PushTemplatesFromSourceToGenerateItems();
            GenerateFromList();
        }

        private void lnkAddProcedure_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            TransformTemplate template = cboTemplates.SelectedItem as TransformTemplate;

            if (tabSource.SelectedIndex == 0)
            {
                // Get the selected items
                SchemaStoredProcedure sproc = cboProcedures.SelectedItem as SchemaStoredProcedure;
                SchemaTable table = cboTables.SelectedItem as SchemaTable;
                string connectionSource = (string)cboConnectionStrings.SelectedItem;

                if (sproc == null)
                {
                    return;
                }

                var tag = new TransformInstructions()
                {
                    ProcedureFromSchema = sproc.Clone() as SchemaStoredProcedure,
                    TableFromSchema = table,
                    Template = template.Clone() as TransformTemplate,
                    SourcedFromConnection = connectionSource,
                    ListSource = GetSelectedList()
                };

                using (ParameterEntryDialog f = new ParameterEntryDialog(tag, true))
                {
                    if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        CreateLviForProcedure(tag);
                        GenerateFromList();
                    }
                }
            }
            else if (tabSource.SelectedIndex == 1)
            {
                var tag = new TransformInstructions()
                {
                    Template = template.Clone() as TransformTemplate,
                    ListSource = GetSelectedList()
                };
                CreateLviForProcedure(tag);
                GenerateFromList();
            }

            SaveProfileFromUI();
            UpdateUI();
        }

        private ListViewItem CreateLviForProcedure(TransformInstructions p, int insertAt = -1)
        {
            if (insertAt == -1)
                insertAt = lstToGenerate.Items.Count;

            string itemName = p.ProcedureFromSchema != null ? p.ProcedureFromSchema.SPECIFIC_NAME : p.ListSource.Name;

            var lvi = lstToGenerate.Items.Insert(insertAt, new ListViewItem(itemName));
            lvi.Tag = p;

            if (p.ProcedureFromSchema != null && p.ProcedureFromSchema.ExecuteForData)
                lvi.ForeColor = Color.Green;
            if (p.Template != null)
                lvi.SubItems.Add(p.Template.Name);

            return lvi;

        }

        private void lnkDelete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (lstToGenerate.SelectedItems.Count == 0)
                return;

            var lvi = lstToGenerate.SelectedItems[0];
            lvi.Remove();

            GenerateFromList();
            SaveProfileFromUI();

        }

        private void lnkModify_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            // Get the selected items
            //SchemaStoredProcedure sproc = cboProcedures.SelectedItem as SchemaStoredProcedure;
            //TransformTemplate template = cboTemplates.SelectedItem as TransformTemplate;
            //SchemaTable table = cboTables.SelectedItem as SchemaTable;

            string connectionSource = (string)cboConnectionStrings.SelectedItem;
            ListViewItem lvi = lstToGenerate.SelectedItems[0];
            if (lvi == null || lvi.Tag == null)
            {
                return;
            }
            TransformInstructions tag = lvi.Tag as TransformInstructions;

            // Clone the procedure, then copy it back if we're OK with the changes
            using (ParameterEntryDialog f = new ParameterEntryDialog(tag))
            {
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (tag.ProcedureFromSchema.ExecuteForData)
                        lvi.ForeColor = Color.Green;
                    GenerateFromList();
                }
            }

            UpdateUI();
            SaveProfileFromUI();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            Refresh_Db();
            UpdateUI();
        }

        private void tabSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateUI();
        }

        private void tvLists_AfterSelect(object sender, TreeViewEventArgs e)
        {
            UpdateUI();
        }

        private void UpdateUI()
        {

            bool isListSelected = (GetSelectedList() != null);
            lnkAddProcedure.Enabled = ((tabSource.SelectedIndex == 0 && cboProcedures.SelectedItem != null) || (tabSource.SelectedIndex == 1 && isListSelected)) 
                                        && (cboTemplates.SelectedItem != null);
            lnkDelete.Enabled = (lstToGenerate.FocusedItem != null);
            lnkModify.Enabled = (lstToGenerate.FocusedItem != null);
            lnkSourceUp.Enabled = (lstToGenerate.FocusedItem != null) && (lstToGenerate.FocusedItem.Index > 0);
            lnkSourceDown.Enabled = (lstToGenerate.FocusedItem != null) && ((lstToGenerate.FocusedItem.Index >= 0) && (lstToGenerate.FocusedItem.Index < (lstToGenerate.Items.Count - 1)));
            lnkCopyLiveTemplateToSource.Enabled = (m_CurrentProcedure != null);
        }

        private void lstToGenerate_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstToGenerate.SelectedItems.Count > 0)
            {
                var lvi = lstToGenerate.SelectedItems[0];
                var tag = lvi.Tag as TransformInstructions;
                ShowGeneratedItemFromList(tag);
            }
            else
            {
                ShowGeneratedItemFromList(null);
            }
            SaveProfileFromUI();
        }

        private void lnkSourceUp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var lvi = lstToGenerate.FocusedItem;
            if (lvi == null)
                return;

            TransformInstructions tag = lvi.Tag as TransformInstructions;
            int index = lvi.Index;

            if (index > 0)
            {
                lvi.Remove();
                lvi = CreateLviForProcedure(tag, index - 1);
            }

            SaveProfileFromUI();
            lvi.Selected = true;
            lvi.Focused = true;

            UpdateUI();
        }

        private void lnkSourceDown_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var lvi = lstToGenerate.FocusedItem;
            if (lvi == null)
                return;

            TransformInstructions tag = lvi.Tag as TransformInstructions;
            int index = lvi.Index;

            if ((index >= 0) && (index < (lstToGenerate.Items.Count - 1)))
            {
                lvi.Remove();
                lvi = CreateLviForProcedure(tag, index + 1);
            }

            SaveProfileFromUI();
            lvi.Selected = true;
            lvi.Focused = true;

            UpdateUI();
        }

        private void ShowGeneratedItemFromList(TransformInstructions tag)
        {
            m_CurrentProcedure = tag;
            m_IsLoading = true;

            txtTransform.Text = tag != null ? tag.TransformedText : "";
            txtTransform.Document.RequestUpdate(new ICSharpCode.TextEditor.TextAreaUpdate(ICSharpCode.TextEditor.TextAreaUpdateType.WholeTextArea));

            txtLiveTemplate.Text = tag != null ? tag.Template.Template : "";
            txtLiveTemplate.Document.RequestUpdate(new ICSharpCode.TextEditor.TextAreaUpdate(ICSharpCode.TextEditor.TextAreaUpdateType.WholeTextArea));

            if (tag != null)
            {
                var highlightingStrategy = (tag.Template.Syntax.ToLower() == "vb.net" ? "VBNET" : "C#");
                txtTransform.SetHighlighting(highlightingStrategy);

                highlightingStrategy = (tag.Template.Syntax.ToLower() == "vb.net" ? "VBNET" : "C#");
                txtLiveTemplate.SetHighlighting(highlightingStrategy);

                //ICSharpCode.TextEditor.Document.DefaultHighlightingStrategy newHs = new ICSharpCode.TextEditor.Document.DefaultHighlightingStrategy();
                //newHs.SetColorFor("Default", new ICSharpCode.TextEditor.Document.HighlightColor(Color.Black, Color.FromArgb(235, 241, 221), false, false));
                //txtLiveTemplate.Document.HighlightingStrategy = newHs;
            }

            m_IsLoading = false;
            UpdateUI();
        }

        private void GenerateFromList()
        {
            PushTemplatesFromSourceToGenerateItems();

            var toProcess = new List<TransformInstructions>();
            foreach (ListViewItem lvi in lstToGenerate.Items)
            {
                var tag = lvi.Tag as TransformInstructions;
                toProcess.Add(tag);
            }

            Task t = new Task(() =>
            {
                TemplateHelper.DoTransforms(toProcess.ToArray());
            });

            t.ContinueWith((x) =>
            {
                if (lstToGenerate.SelectedItems.Count == 0 && lstToGenerate.Items.Count > 0)
                {
                    lstToGenerate.Items[0].Selected = true;
                }
                lstToGenerate_SelectedIndexChanged(lstToGenerate, new EventArgs());
                UpdateUI();
            }, TaskScheduler.FromCurrentSynchronizationContext());

            t.Start();

        }

        private void txtLiveTemplate_TextChanged(object sender, EventArgs e)
        {
            if (m_CurrentProcedure != null && !m_IsLoading)
            {
                m_CurrentProcedure.Template.Template = txtLiveTemplate.Text;
                var vScroll = txtTransform.ActiveTextAreaControl.VScrollBar.Value;
                //var curPos = txtTransform.ActiveTextAreaControl.Caret.Position;

                Task t = new Task(() =>
                {
                    TemplateHelper.DoTransforms(m_CurrentProcedure);
                });

                t.ContinueWith((x) =>
                {
                    try
                    {
                        txtTransform.BeginUpdate();

                        txtTransform.Text = m_CurrentProcedure.TransformedText;
                        txtTransform.Document.RequestUpdate(new ICSharpCode.TextEditor.TextAreaUpdate(ICSharpCode.TextEditor.TextAreaUpdateType.WholeTextArea));

                        txtTransform.EndUpdate();
                        
                        txtTransform.ActiveTextAreaControl.VScrollBar.Value = vScroll;
                        //txtTransform.ActiveTextAreaControl.Caret.Position = curPos;
                        m_CurrentProcedure.Template.Template = txtLiveTemplate.Text;

                        SaveProfileFromUI();
                    }
                    catch
                    {
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());

                t.Start();
            }
        }

        private void lnkCopyLiveTemplateToSource_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var templates = TemplateHelper.GetTemplates();
            if (m_CurrentProcedure != null && !m_IsLoading)
            {
                foreach (var item in templates)
                {
                    if (item.FileName == m_CurrentProcedure.Template.FileName)
                    {
                        item.Template = txtLiveTemplate.Text;
                        TemplateHelper.Save(item, item.FileName);
                    }
                }
            }
            PushTemplatesFromSourceToGenerateItems();
        }

        private void spltTemplate_DoubleClick(object sender, EventArgs e)
        {
            spltTemplate.Orientation = spltTemplate.Orientation == Orientation.Horizontal ? Orientation.Vertical : Orientation.Horizontal;
        }

        private void lnkAddList_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (m_CurrentProfile == null)
                return;

            ListWithName newList = null;
            string newListName = "New List " + (m_CurrentProfile.ListSource.Count + 1).ToString();

            using (NewListDialog f = new NewListDialog(newListName))
            {
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                   newList = new ListWithName(f.ListName);
                }
            }

            if (newList == null)
                return;

            using (ListEditorDialog f = new ListEditorDialog(newList))
            {
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {

                }
            }

            if (m_CurrentProfile.ListSource == null)
                m_CurrentProfile.ListSource = new List<ListWithName>();

            m_CurrentProfile.ListSource.Add(newList);
            SaveProfileFromUI();
            Load_Lists();
        }
        
        private void lnkModifyList_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            var list = GetSelectedList();

            if (list == null)
                return;

            using (ListEditorDialog f = new ListEditorDialog(list))
            {
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    SaveProfileFromUI();
                    Load_Lists();
                }
            }
        }

        private void lnkDeleteList_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (tvLists.SelectedNode == null)
                return;

            var tag = tvLists.SelectedNode.Tag as ListWithName;
            // Get it's parent
            if (tvLists.SelectedNode.Parent != null)
            {
                var parentTag = tvLists.SelectedNode.Parent.Tag as ListWithName;
                parentTag.ChildLists.Remove(tag);
            }
            else
            {
                m_CurrentProfile.ListSource.Remove(tag);
            }

            SaveProfileFromUI();
            Load_Lists();
        }

        private ListWithName GetSelectedList()
        {
            if (tvLists.SelectedNode == null)
                return null;

            var tag = tvLists.SelectedNode.Tag as ListWithName;
            var parent = tvLists.SelectedNode.Parent;

            while (parent != null)
            {
                tag = parent.Tag as ListWithName;
                parent = parent.Parent;
            }
            return tag;

        }


    }
}
